﻿// See https://aka.ms/new-console-template for more information
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSwaggerGen();
builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();


app.MapPost("/邮件发送", (string mailTo, string mailTile, string mailContent) =>
{
    string smtpServer = @"smtp.163.com";
    string mailAccount = @"13272143617@163.com";
    string pwd = @"CBXEAODWCAMERKQX";
    SmtpClient smtpClient = new SmtpClient();
    smtpClient.Host = smtpServer;
    smtpClient.Port = 25;
    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//默认network
    smtpClient.EnableSsl = true;
    //smtpClient.UseDefaultCredentials = true; //打开这个会报错，无法发送邮件
    smtpClient.Credentials = new NetworkCredential(mailAccount, pwd);

    MailMessage mailMessage = new MailMessage(mailAccount, mailTo);
    mailMessage.Subject = mailTile;
    mailMessage.Body = mailContent;
    mailMessage.IsBodyHtml = true;
    mailMessage.BodyEncoding = Encoding.UTF8;

    //添加附件

    //两种形式，一种是直接添加文件流，一种是添加本地文件
    var path = @"c:/a/b/c/123.txt";
    Attachment data1 = new Attachment(path);
    mailMessage.Attachments.Add(data1);

    ////一种是直接添加文件流
    ////切记将流的位置重置到开始
    //Attachment data = new Attachment(new FileStream(), new ContentType()
    //{
    //    MediaType = MediaTypeNames.Application.Pdf,
    //    Name = "attachment_name.pdf"
    //});
    //mailMessage.Attachments.Add(data);


    mailMessage.IsBodyHtml = false;
    mailMessage.Priority = MailPriority.Normal;

    smtpClient.Send(mailMessage);
});

app.Run();